package com.kkd.kkdapp.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.MyRecommendFriendAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.InviteFriendShare;
import com.kkd.kkdapp.http.entity.MyRecommendFriendData;
import com.kkd.kkdapp.http.entity.MyRecommendFriendDataList;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.Time_Date;
import com.kkd.kkdapp.view.KkdXlistView;
import com.kkd.kkdapp.view.KkdXlistView.KKDScrollListener;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的一度好友
 * 
 * @author mty
 * 
 */
public class MyRecommendFriendActivity extends BaseActivity implements
		OnClickListener, KKDScrollListener {

	private static final int NO_MORE_FRIEND = 1;
	private static final int GET_FRIENDS_SUCCESS = 2;
	private static final int GET_FRIENDS_FAILURE = 3;

	private ImageView retreat; // 返回键
	private LinearLayout regulation_ll; // 邀请攻略
	private LinearLayout share_ll; // 邀请好友
	private KkdXlistView mXListView;
	private ImageView img_null;
	private TextView tv_null;
	private List<MyRecommendFriendDataList> dateList = new ArrayList<MyRecommendFriendDataList>();
	private MyRecommendFriendAdapter mAdapter;
	private int pageNO = 1;
	private int pageSize = 10;
	private boolean REFRESHFLAG = true;
	private String inviteStrategyUrl = null; // 邀请攻略Url
	private LinearLayout mytwocode_ll; // 我的二维码
	private EditText seek_friend; // 搜索框
	private RelativeLayout ed_clean; // 清除搜索框
	private View line_seek;
	private RelativeLayout seek; // 搜索
	private boolean seekflag = true; // 是否查找全部好友 ，如果是检索部分好友则为false
	private RelativeLayout advocate_rl;
	private ImageView seek_img;
	private RelativeLayout tip;
	private ImageView iv_ad;
	private TextView tv_bottom;
	private View seek_friend_rl;
	private MyRecommendFriendData data;
	private InviteFriendShare inviteFriendShare;
	// private String inviteFriendUrl;

	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			String time = "";
			switch (msg.what) {
			case NO_MORE_FRIEND:
				tip.setVisibility(View.GONE);
				mXListView.stopLoadMore(-1);
				if (REFRESHFLAG || !seekflag) {
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							mXListView.stopLoadMore(0);
						}
					}, 0);
				}
				mXListView.stopRefresh();
				mAdapter.notifyDataSetChanged();
				if (REFRESHFLAG || !seekflag) {
					img_null.setVisibility(View.VISIBLE);
					tv_null.setVisibility(View.VISIBLE);
				}
				if (!seekflag) {// 在检索某个好友
					tv_null.setText("抱歉，暂无该好友的相关信息");
					seek_friend_rl.setVisibility(View.VISIBLE);
					dateList.clear();
					mAdapter.notifyDataSetChanged();
				} else if (dateList == null || dateList.size() == 0) {
					tv_null.setText("暂无好友，赶紧邀请好友吧~");
					seek_friend_rl.setVisibility(View.GONE);
				}
				String inviteFriendImageUrl2 = data.getInviteFriendImageUrl();
				ImageLoader.getInstance().displayImage(inviteFriendImageUrl2,
						iv_ad, R.drawable.home_ad);
				break;
			case GET_FRIENDS_SUCCESS:
				if (!seekflag) {
					if (dateList == null) {
						// mXListView.setPullRefreshEnable(false);
						img_null.setVisibility(View.VISIBLE);
						tv_null.setVisibility(View.VISIBLE);
						tv_null.setText("为搜索到结果");
						seek_friend_rl.setVisibility(View.VISIBLE);
					} else {
						if (dateList.size() > 0) {
							mXListView.setNoMore(false);
							mXListView.setVisibility(View.VISIBLE);
							img_null.setVisibility(View.GONE);
							tv_null.setVisibility(View.GONE);
							seek_friend_rl.setVisibility(View.VISIBLE);
							if (dateList.size() < pageSize) {
								mXListView.stopLoadMore(1);
							} else {
								mXListView.stopLoadMore(0);
							}
						} else {
							mXListView.setVisibility(View.GONE);
							img_null.setVisibility(View.VISIBLE);
							tv_null.setVisibility(View.VISIBLE);
							tv_null.setText("为搜索到结果");
							seek_friend_rl.setVisibility(View.VISIBLE);
						}
					}
				} else {
					if (dateList == null) {
						// mXListView.setPullRefreshEnable(false);
						img_null.setVisibility(View.VISIBLE);
						tv_null.setVisibility(View.VISIBLE);
						tv_null.setText("为搜索到结果");
						seek_friend_rl.setVisibility(View.GONE);
					} else {
						if (dateList.size() > 0) {
							LogUtil.e("qqqqqqq1", "");
							mXListView.setVisibility(View.VISIBLE);
							img_null.setVisibility(View.GONE);
							tv_null.setVisibility(View.GONE);
							seek_friend_rl.setVisibility(View.VISIBLE);
						} else {
							LogUtil.e("qqqqqqq2", "");
							mXListView.setVisibility(View.GONE);
							img_null.setVisibility(View.VISIBLE);
							tv_null.setVisibility(View.VISIBLE);
							tv_null.setText("为搜索到结果");
							seek_friend_rl.setVisibility(View.GONE);
						}
					}
				}
				// mAdapter.update();
				// mAdapter.appendData(dateList, pageNO == 1);
				mAdapter.notifyDataSetChanged();
				if (data.getDataList().size() < pageSize) {
					mXListView.stopLoadMore(1);
				} else {
					mXListView.stopLoadMore(0);
				}
				mXListView.stopRefresh();
				time = new Time_Date().get_Year_Day();
				mXListView.setRefreshTime(time);
				tip.setVisibility(View.GONE);
				String inviteFriendImageUrl = data.getInviteFriendImageUrl();
				ImageLoader.getInstance().displayImage(inviteFriendImageUrl,
						iv_ad, R.drawable.home_ad);
				break;
			case GET_FRIENDS_FAILURE:
				int statusCode = (Integer) msg.obj;
				img_null.setVisibility(View.VISIBLE);
				tv_null.setVisibility(View.VISIBLE);
				seek_friend_rl.setVisibility(View.VISIBLE);
				img_null.setImageResource(R.drawable.img_null_net);
				if (statusCode == KkdHttpClient.NO_NET) {
					tv_null.setText("网络错误，请稍后重试");
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					tv_null.setText("服务异常，请稍后重试");
				}
				mXListView.stopLoadMore(1);
				mXListView.stopRefresh();
				tip.setVisibility(View.GONE);
				break;
			default:
				break;
			}
			if (seekflag) {
				if (REFRESHFLAG) {
					LogUtil.e("dateList", "" + dateList);
					if (dateList == null || dateList.size() <= 0) {
						// mXListView.setPullLoadEnable(false);
						img_null.setVisibility(View.VISIBLE);
						tv_null.setVisibility(View.VISIBLE);
						seek_friend_rl.setVisibility(View.GONE);
					} else {
						// mXListView.setPullLoadEnable(true);
						img_null.setVisibility(View.GONE);
						tv_null.setVisibility(View.GONE);
					}
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		inviteFriendShare = PreferenceUtils.getInstance().getInviteFriend(this);
		setContentView(R.layout.activity_my_recommend_friend);
		initUI();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kkd.kkdapp.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (PreferenceUtils.getInstance().getLogin(this) != 0) {
			finish();
		}
		searchFriend();

	}

	/**
	 * 组件初始化
	 */
	public void initUI() {
		View headerView = LayoutInflater.from(this).inflate(
				R.layout.head_myfriends, null);
		// LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
		// SystemUtils.dip2px(this, 164));
		// headerView.setLayoutParams(params);
		iv_ad = (ImageView) headerView.findViewById(R.id.iv_ad);
		seek_friend_rl = headerView.findViewById(R.id.seek_friend_rl);
		seek_friend = (EditText) headerView.findViewById(R.id.seek_friend);
		ed_clean = (RelativeLayout) headerView.findViewById(R.id.ed_clean);
		line_seek = headerView.findViewById(R.id.line_seek);
		seek = (RelativeLayout) headerView.findViewById(R.id.seek);
		seek_img = (ImageView) headerView.findViewById(R.id.seek_img);
		tip = (RelativeLayout) headerView.findViewById(R.id.tip);

		tv_bottom = (TextView) findViewById(R.id.tv_bottom);
		retreat = (ImageView) this.findViewById(R.id.retreat);
		share_ll = (LinearLayout) this.findViewById(R.id.share_ll);
		regulation_ll = (LinearLayout) this.findViewById(R.id.regulation_ll);
		mXListView = (KkdXlistView) this
				.findViewById(R.id.myrecommendfriend_lv);
		img_null = (ImageView) this.findViewById(R.id.img_null);
		tv_null = (TextView) this.findViewById(R.id.tv_null);
		mytwocode_ll = (LinearLayout) this.findViewById(R.id.mytwocode_ll);
		advocate_rl = (RelativeLayout) this.findViewById(R.id.advocate_rl);

		iv_ad.setOnClickListener(this);
		tv_bottom.setOnClickListener(this);
		mXListView.mListView.setDividerHeight(0);
		mXListView.mListView.setPadding(0, 0, 0, 0);
		mXListView.setKKDScrollListener(this);
		mAdapter = new MyRecommendFriendAdapter(this, dateList);
		mXListView.mListView.addHeaderView(headerView);
		mXListView.setAdapter(mAdapter);
		mXListView.startRefresh();
		retreat.setOnClickListener(this);
		regulation_ll.setOnClickListener(this);
		share_ll.setOnClickListener(this);
		mytwocode_ll.setOnClickListener(this);
		// mXListView.setXListViewListener(this);
		seek_friend.setOnClickListener(this);
		ed_clean.setOnClickListener(this);
		advocate_rl.setOnClickListener(this);
		seek.setOnClickListener(this);
		// mXListView.setPullRefreshEnable(true);
		// mXListView.setPullLoadEnable(false);
		seek_friend.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!s.toString().equals("")) {
					seek_img.setImageResource(R.drawable.selector_seek);
					ed_clean.setVisibility(View.VISIBLE);
					// line_seek.setVisibility(View.VISIBLE);
				} else if ("".equals(getSeekText())) {
					seek_img.setImageResource(R.drawable.unselector_seek);
					ed_clean.setVisibility(View.INVISIBLE);
					// line_seek.setVisibility(View.INVISIBLE);
					if (!seekflag) {
						searchFriend();
						mXListView.setNoMore(false);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		RelativeLayout share_bt = (RelativeLayout) findViewById(R.id.share_bt);
		share_bt.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.retreat: // 返回键
			PreferenceUtils.getInstance().setMyproperty(this, "");
			finish();
			seek_friend.setFocusable(false);
			break;
		case R.id.regulation_ll: // 邀请攻略
		case R.id.iv_ad: // 邀请攻略
			SystemUtils.onEvent("Discovery_InviteFrinds_Strategy", 1);
			if (inviteStrategyUrl != null) {
				Intent intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("titleName", "邀请攻略");
				intent.putExtra("url", inviteStrategyUrl);
				startActivity(intent);
			}
			seek_friend.setFocusable(false);
			break;
		case R.id.share_bt:
		case R.id.share_ll: // 邀请好友
		case R.id.tv_bottom: // 邀请好友
			if (inviteFriendShare != null) {
				PreferenceUtils.getInstance().setH5Entrance(this, "邀请好友攻略");
				SystemUtils.onEvent("Discovery_InviteFrinds_Deatil_Invite", 1);
				toShareURL(MyRecommendFriendActivity.this,
						inviteFriendShare.getInviteFriendUrl(),
						inviteFriendShare.getTitle(),
						inviteFriendShare.getDesc(),
						inviteFriendShare.getImageUrl());
				seek_friend.setFocusable(false);
			}
			break;
		case R.id.mytwocode_ll: // 我的二维码
			Intent intent = new Intent(this, MyQrcodeActivity.class);
			startActivity(intent);
			seek_friend.setFocusable(false);
			break;
		case R.id.seek_friend: // 搜素框
			seekFrame();
			mXListView.setNoMore(false);
			break;
		case R.id.ed_clean: // 清空搜索框
			seek_friend.setText("");
			break;
		case R.id.seek: // 搜索
			tip.setVisibility(View.VISIBLE);
			searchFriend();
			break;
		case R.id.advocate_rl:
			seek_friend.setFocusable(false);
			break;

		}
	}

	/**
	 * 
	 * 搜索框处理
	 */
	public void seekFrame() {
		seek_friend.setFocusable(true);
		seek_friend.setFocusableInTouchMode(true);
		seek_friend.requestFocus();
	}

	/**
	 * 一度好友接口
	 */
	public void questFriend(String search) {
		seekflag = TextUtils.isEmpty(search);
		String custmeridAndToken = PreferenceUtils.getInstance().getcustomerId(
				this);
		String[] cat = custmeridAndToken.split("&");
		if (cat == null || cat.length < 2)
			return;
		KkdHttpMagager.getInstance().getMyRecommendFriendManager(search,
				pageNO, pageSize, MyRecommendFriendData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						data = (MyRecommendFriendData) responseBody;
						inviteStrategyUrl = data.getInviteStrategyUrl();
						int pageCount = data.getPageCount();
						int pageNo = data.getPageNO();
						if (pageNo == 1)
							dateList.clear();
						if (pageNo > pageCount) {
							handler.sendEmptyMessage(NO_MORE_FRIEND);
						} else {
							for (MyRecommendFriendDataList i : data
									.getDataList()) {
								boolean isContain = false;
								for (MyRecommendFriendDataList j : dateList) {
									if (j.getCustomerId().equals(
											i.getCustomerId())) {
										isContain = true;
										break;
									}
								}
								if (isContain) {
									continue;
								} else {
									dateList.add(i);
								}
							}
							handler.sendEmptyMessage(GET_FRIENDS_SUCCESS);
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.obj = statusCode;
						msg.what = GET_FRIENDS_FAILURE;
						handler.sendMessage(msg);
					}
				});

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
			searchFriend();
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	public String getSeekText() {
		String str = null;
		try {
			str = seek_friend.getText().toString();
		} catch (Exception e) {
			// 字符串为空
		}
		return str;
	}

	public void searchFriend() {
		/* 隐藏软键盘 */

		SystemUtils.hideKeyBoard(MyRecommendFriendActivity.this);
		String str = getSeekText();

		if (!TextUtils.isEmpty(str)) {
			questFriend(str);
		} else {
			questFriend("");
		}

	}

	@Override
	public void onRefresh() {
		pageNO = 1;
		mAdapter.clearTwoFriendData();
		// dateList.clear();
		searchFriend();
		REFRESHFLAG = true;
	}

	@Override
	public void onLoadMore() {
		if (AppUtil.isConnect(this)) {
			pageNO++;
			REFRESHFLAG = false;
		}
		searchFriend();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
